import { Descriptions, Divider, message, Skeleton, Tabs, Tooltip, Empty, List, Space, PageHeader ,Modal} from 'antd';
import { PRIORUTY_LEVEL, DEAMEN_STATUS } from '@/consts/project'
import { connect, history, Link } from 'umi';
import { ClockCircleOutlined } from '@ant-design/icons'
import { useEffect } from 'react';
import EditAble from '../../../../components/EditAble'
import { DemandStatus } from './index'
import RichText, { RichTextEdit } from '@/components/RichText'
import UserBrief from '@/components/UserBrief'
import ArrayUtils from '@/utils/ArrayUtils'
import styles from './style.less'
import PriorityLevel from '../PriorityLevel'
import DemandTarget from './DemandTarget'
import { useState } from 'react';
import { formetDate } from '@/utils/dateUtils'
import { ProdStatus } from '../ProjectProduct';
const { TabPane } = Tabs;
import { updateDemand as updateDemandService, getDetail, deleteDemand,updateIsArchived} from '@/services/project/demand'
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import { addItemLog } from '@/services/project/itemLog'
import ActionDropdown from '@/components/ActionDropdown';
import TextButton from '@/components/TextButton';


const DemandDetail = (props) => {
    const {
        projectId,
        demandId,
        dispatch,
        projectPermission
    } = props



    const [isDetailTextEditFlag, setIsDetailTextEditFlag] = useState(false)
    const [isTargetEditFlag, setIsTargetEditFlag] = useState(false)
    const [isBackgroundTextEditFlag, setIsBackgroundTextEditFlag] = useState(false)
    const [demandDetail, setDemandDetail] = useState()
    const [projectLogUpdate, setProjectLogUpdate] = useState(0);
    const [tabKey, setTabKey] = useState();
    const [permission, setPermission] = useState({})

    useEffect(() => {
        if (projectId && demandId) {
            getDetail(projectId, demandId).then(({ data }) => {
                setDemandDetail(data);
            })
        }
    }, [projectId, demandId])

    useEffect(() => {
        setIsBackgroundTextEditFlag(false);
        setIsDetailTextEditFlag(false);
        setIsTargetEditFlag(false)
    }, [demandDetail])

    useEffect(() => {
        setPermission({
            ...projectPermission?.prod
        })
    }, [projectPermission])

    if (!demandDetail || demandDetail.id !== demandId) {
        return <div className={styles.detailContainer}><Skeleton></Skeleton></div>
    }

    const updateDemandUser = (userId, user) => {
        updateDemand({
            userId: userId,
            payload: {
                userId: user.nickName
            },
            oldData: {
                userId: demandDetail.userId,
                payload: {
                    userId: demandDetail.user?.nickName
                }
            }
        })
        demandDetail.userId = userId;
        demandDetail.user = user;
        setDemandDetail({ ...demandDetail })
    }

    const updateDemandToUser = (userId, user) => {
        updateDemand({
            toUserId: userId,
            payload: {
                toUserId: user.nickName
            },
            oldData: {
                userId: demandDetail.toUserId,
                payload: {
                    toUserId: demandDetail.toUser?.nickName
                }
            }
        })
        demandDetail.toUserId = userId;
        demandDetail.toUser = user;
        setDemandDetail({ ...demandDetail })
    }

    const updateProjectStatus = (status) => {
        updateDemand({
            status: status,
            oldData: {
                status: demandDetail.status
            }
        })
        demandDetail.status = status;
        setDemandDetail({ ...demandDetail })
    }

    const updatePlanDate = (planDates) => {
        console.log(planDates)
        updateDemand({
            planStartDate: planDates[0],
            planEndDate: planDates[1],
            oldData: {
                planStartDate: demandDetail.planStartDate,
                planEndDate: demandDetail.planEndDate
            }
        })
        demandDetail.planStartDate = planDates[0];
        demandDetail.planEndDate = planDates[1];
        setDemandDetail({ ...demandDetail })
    }

    const updateActualDate = (actualDate) => {
        updateDemand({
            actualStartDate: actualDate[0],
            actualEndDate: actualDate[1],
            oldData: {
                actualStartDate: demandDetail.actualStartDate,
                actualEndDate: demandDetail.actualEndDate
            }
        })
        demandDetail.actualStartDate = actualDate[0];
        demandDetail.actualEndDate = actualDate[1];
        setDemandDetail({ ...demandDetail })
    }

    const updatePriorityLevel = (priorityLevel) => {
        updateDemand({
            priorityLevel: priorityLevel,
            oldData: {
                priorityLevel: demandDetail.priorityLevel
            }
        })
        demandDetail.priorityLevel = priorityLevel;
        setDemandDetail({ ...demandDetail })
        if (onDetailChange) {
            onDetailChange({
                id: demandId,
                priorityLevel: priorityLevel
            })
        }
    }

    const updateDesc = (description) => {
        updateDemand({
            description: description,
            oldData: {
                description: demandDetail.description
            }
        })
        demandDetail.description = description;
        setDemandDetail({ ...demandDetail })
    }
    const updateName = (name) => {
        updateDemand({
            name: name,
            oldData: {
                name: demandDetail.name
            }
        })
        demandDetail.name = name;
        setDemandDetail({ ...demandDetail })
    }

    const updateDemandContent = (content) => {
        const oldDataContent = {
            content: {
                text: demandDetail.content.text
            }
        };
        updateDemand({
            content: content,
            oldData: oldDataContent
        })
        demandDetail.content = content;
        setDemandDetail({ ...demandDetail })
        setIsDetailTextEditFlag(false)
    }

    const updateDemandBackground = (content) => {
        updateDemand({
            background: content.text,
            oldData: {
                background: demandDetail.background
            }
        })
        demandDetail.background = content.text;
        setDemandDetail({ ...demandDetail })
        setIsBackgroundTextEditFlag(false)
    }

    const updateDemandTarget = (target) => {
        const oldTarget = demandDetail.target
        updateDemand({
            target: {
                list: target.list
            },
            oldData: {
                target: oldTarget
            }
        })
        demandDetail.target = target;
        setDemandDetail({ ...demandDetail })
        setIsTargetEditFlag(false)
    }

    const updateDemandTargetObtain = (index, record) => {
        console.log(index, record)
        demandDetail.target.list[index] = record
        if (record.isObtain === 1) {
            addItemLog(demandDetail.projectId, "demand", demandDetail.id, `编辑完成了期望 ${record.name}`)
        } else {
            addItemLog(demandDetail.projectId, "demand", demandDetail.id, `修改期望 ${record.name} 为未完成`)
        }
        updateDemand({
            target: {
                list: demandDetail.target.list
            },
        })
        demandDetail.target = { ...demandDetail.target }
        setDemandDetail({ ...demandDetail })
    }

    const updateDemand = (data) => {
        updateDemandService(projectId, demandId, data).then(({ success }) => {
            if (success) {
                message.success("保存成功！")
            }
            if (tabKey === "log") {
                setProjectLogUpdate(projectLogUpdate + 1)
            }
        })
    }

    const updatItemIsArchived = (isArchived) => {
        let title = ""
        if (isArchived === 1) {
            title = '确认归档，归档之后无法编辑，只能在归档列表中显示'
        } else {
            title = "确认撤销归档"
        }
        Modal.confirm({
            title: title,
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                updateIsArchived(projectId, demandId, isArchived)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            setDemandDetail({
                                ...demandDetail,
                                isArchived: isArchived
                            })
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const deleteItem = () => {
        Modal.confirm({
            title: '确认删除，删除之后将无法恢复',
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                deleteDemand(projectId, demandId)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            history.push(`/projects/${projectId}/demand`)
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    if (!demandId) {
        return <div className={styles.demandDetail}><Empty></Empty></div>
    }

    return (
        <div className={styles.detailContainer}>
            <PageHeader
                onBack={() => history.go(-1)}
                title={<EditAble permission={permission}
                    value={demandDetail.name}
                    onSave={updateName}
                    type="input">
                    {demandDetail.name}
                </EditAble>}
                extra={[
                    <ActionDropdown
                        key="action"
                        className={styles.actionDropdown}
                        placement="bottomLeft"
                        actions={[
                            demandDetail?.isArchived === 0 ?
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(1)
                                }}>归档</TextButton> :
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(0)
                                }}>撤销归档</TextButton>
                            ,
                            <TextButton key="delete" type="danger" onClick={() => {
                                deleteItem()
                            }}>删除</TextButton>]}
                    />
                ]}
            >
                <Descriptions size="small" column={3}>
                    <Descriptions.Item label="负责人">
                        <EditAble permission={permission}
                            value={demandDetail.userId}
                            editComponentProps={{
                                projectId: projectId,
                                defaultOpen: true
                            }}
                            onSave={updateDemandUser}
                            type="userSelect">
                            <UserBrief user={demandDetail.user}></UserBrief>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="状态">
                        <EditAble permission={permission}
                            value={demandDetail.status}
                            editComponentProps={{
                                options: ArrayUtils.jsonToArray(DEAMEN_STATUS).map(item => {
                                    return { value: item.key, label: item.value.name }
                                }),
                                defaultOpen: true
                            }}
                            onSave={updateProjectStatus}
                            type="select">
                            <DemandStatus status={demandDetail.status}></DemandStatus>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="优先级" span={1}>
                        <EditAble permission={permission}
                            value={demandDetail.priorityLevel}
                            editComponentProps={{
                                options: ArrayUtils.jsonToArray(PRIORUTY_LEVEL).map(item => {
                                    return { value: item.key, label: item.value.name }
                                }),
                                defaultOpen: true
                            }}
                            onSave={updatePriorityLevel}
                            type="select">
                            <PriorityLevel priorityLevel={demandDetail.priorityLevel}></PriorityLevel>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="需求方" span={1}>{demandDetail.demandSource && demandDetail.demandSource.name}</Descriptions.Item>
                    <Descriptions.Item label="指派给" span={1} >
                        <EditAble permission={permission}
                            value={demandDetail.toUserId !== "0" ? demandDetail.toUserId : ""}
                            editComponentProps={{
                                projectId: projectId,
                                defaultOpen: true
                            }}
                            onSave={updateDemandToUser}
                            type="userSelect">
                            <UserBrief user={demandDetail.toUser}></UserBrief>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间" span={1}>{demandDetail.createTime}</Descriptions.Item>
                    <Descriptions.Item label="排期" span={3}>
                        <EditAble permission={permission}
                            value={[demandDetail.actualStartDate, demandDetail.actualEndDate]}
                            editComponentProps={{
                                format: "YYYY-MM-DD"
                            }}
                            onSave={updateActualDate}
                            type="rangePicker">
                            {`${formetDate(demandDetail.actualStartDate)} - ${formetDate(demandDetail.actualEndDate)}`}
                        </EditAble>
                        {demandDetail.planStartDate && <Tooltip placement="topLeft" title={`预计时间:${formetDate(demandDetail.planStartDate)} - ${formetDate(demandDetail.planEndDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>
                    <Descriptions.Item label="概述" span={3} >
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            editComponentProps={{
                                rows: 4,
                                maxLength: 200,
                                showCount: true
                            }}
                            width="80%"
                            onSave={updateDesc}
                            useCustomOperate={true}
                            value={demandDetail.description}
                            type="textarea">
                            <p>
                                {demandDetail.description}
                            </p>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <Divider></Divider>
                    </Descriptions.Item>
                    <Descriptions.Item label="用户故事" span={3} ></Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            isEdit={isBackgroundTextEditFlag}
                            onEdit={() => {
                                setIsBackgroundTextEditFlag(true)
                            }}
                            width="100%"
                            value={demandDetail.background}
                            onCancel={() => {
                                setIsBackgroundTextEditFlag(false)
                            }}
                            onSave={() => {
                                setIsBackgroundTextEditFlag(false)
                            }}
                            useCustomOperate={true}
                            editComponent={
                                <RichTextEdit
                                    size="small"
                                    onCancel={() => {
                                        setIsBackgroundTextEditFlag(false)
                                    }}
                                    onSave={updateDemandBackground}
                                    value={demandDetail.background}>
                                </RichTextEdit>
                            }>
                            <RichText
                                ellipsis
                                border
                                value={demandDetail.background}>
                            </RichText>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="内容" span={3} >
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            isEdit={isDetailTextEditFlag}
                            onEdit={() => {
                                setIsDetailTextEditFlag(true)
                            }}
                            width="100%"
                            value={demandDetail.content.raw}
                            onCancel={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            onSave={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            useCustomOperate={true}
                            editComponent={
                                <RichTextEdit
                                    size="small"
                                    onCancel={() => {
                                        setIsDetailTextEditFlag(false)
                                    }}
                                    onSave={updateDemandContent}
                                    value={demandDetail.content.raw}>
                                </RichTextEdit>
                            }>
                            <RichText
                                ellipsis
                                border
                                value={demandDetail.content.text}>
                            </RichText>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="期望" span={3} >
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            isEdit={isTargetEditFlag}
                            onEdit={() => {
                                setIsTargetEditFlag(true)
                            }}
                            width="100%"
                            value={demandDetail.target.list}
                            onCancel={() => {
                                setIsTargetEditFlag(false)
                            }}
                            onSave={() => {
                                setIsTargetEditFlag(false)
                            }}
                            editComponent={
                                <DemandTarget.Edit defaultValue={demandDetail.target.list}
                                    onCancel={() => {
                                        setIsTargetEditFlag(false)
                                    }}
                                    onSave={updateDemandTarget}></DemandTarget.Edit>
                            }>
                            <DemandTarget onTargetObtain={updateDemandTargetObtain} permission={permission} target={demandDetail.target}></DemandTarget>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="关联迭代" span={3} >
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <List
                            style={{ width: "100%" }}
                            size="small"
                            locale={{ emptyText: '暂无关联迭代' }}
                            dataSource={demandDetail.relProdItemList}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={<Space size={8}><Link to={`/projects/${demandDetail.projectId}/prod/${item.id}`} >{item.name}</Link> <ProdStatus status={item.status}></ProdStatus></Space>}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </Descriptions.Item>
                    <Descriptions.Item span={3} >
                        <Divider></Divider>
                    </Descriptions.Item>
                </Descriptions >
                <Tabs
                    activeKey={tabKey}
                    onChange={(tabKey) => {
                        setTabKey(tabKey)
                    }}
                    defaultActiveKey="comment">
                    <TabPane tab="评论" key="comment">
                        <ProjectComment projectId={projectId} bizId={demandDetail.id} bizType="demand" />
                    </TabPane>
                    <TabPane tab="日志" key="log">
                        <ProjectItemLog
                            projectId={projectId}
                            itemId={demandDetail.id}
                            renderField={(value, fieldName, isDetail) => {
                                if (fieldName === "status") {
                                    return <DemandStatus status={value}></DemandStatus>
                                }
                                if (fieldName === "priorityLevel") {
                                    return <PriorityLevel priorityLevel={value}></PriorityLevel>
                                }
                                if (fieldName === "background") {
                                    if (isDetail) {
                                        return <RichText
                                            ellipsis
                                            value={value}>
                                        </RichText>
                                    }
                                    return "read"
                                }
                                if (fieldName === "target") {
                                    if (isDetail) {
                                        return <DemandTarget target={value} showAction={false}></DemandTarget>
                                    }
                                    return "read"
                                }

                                if (Array.isArray(fieldName) && (fieldName[0] === "actualStartDate" || fieldName[1] === "actualStartDate")) {
                                    return `${formetDate(value["actualStartDate"])} - ${formetDate(value["actualEndDate"])}`
                                }
                            }}
                            renderFieldName={(fieldName) => {
                                if (fieldName === "priorityLevel") {
                                    return "优先级"
                                }
                                if (fieldName === "toUserId") {
                                    return "指派给"
                                }
                                if (fieldName === "background") {
                                    return "用户故事"
                                }
                                if (fieldName === "target") {
                                    return "期望"
                                }
                                if (Array.isArray(fieldName) && (fieldName[0] === "actualStartDate" || fieldName[1] === "actualStartDate")) {
                                    return "排期"
                                }
                            }}
                            renderModalWidth={(fieldName) => {
                                if (fieldName === "target") {
                                    return "auto"
                                }
                                if (fieldName === "background") {
                                    return "auto"
                                }
                            }}
                            update={projectLogUpdate}
                            itemType="demand" />
                    </TabPane>
                </Tabs>
            </PageHeader>
        </div>
    )
}

export default connect(({ }) => ({

}))(DemandDetail);